<template>
  <div>
    <a-modal
        v-model:visible="pageData.visible"
        width="60%"
        :title="pageData.title"
        :destroy-on-close="true"
        @ok="clickModalOk"
        @cancel="handleModalCancel"
    >
      <a-form
          ref="menuAddUpdateFormRef"
          name="menuAddUpdateForm"
          :model="menuAddUpdateForm.data"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 14 }"
      >
        <a-row :gutter="24">
          <a-col span="12">
            <a-form-item
                name="menuName"
                label="菜单名称"
                :rules="[{ required: true, message: '菜单名称不能为空！' }]"
            >
              <a-input
                  v-model:value="menuAddUpdateForm.data.menuName"
                  :maxlength="30"
                  placeholder="请填写菜单名称"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item
                name="parentId"
                label="上级菜单"
                :rules="[{ required: true, message: '上级菜单不能为空！' }]"
            >
              <a-tree-select
                  v-model:value="menuAddUpdateForm.data.parentId"
                  placeholder="请选择上级菜单"
                  :tree-data="pageData.menusDict"
                  :field-names="{ children: 'children', label: 'menuName', key: 'menuId', value: 'menuId' }"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item
                name="orderNum"
                label="显示顺序"
                :rules="[{ required: true, message: '显示顺序不能为空！' }]"
            >
              <a-input
                  v-model:value="menuAddUpdateForm.data.orderNum"
                  :maxlength="30"
                  placeholder="请填写显示顺序"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item name="path" label="路由地址" :rules="[{}]">
              <a-input
                  v-model:value="menuAddUpdateForm.data.path"
                  :maxlength="30"
                  placeholder="请填写路由地址"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item name="component" label="组件路径" :rules="[{}]">
              <a-input
                  v-model:value="menuAddUpdateForm.data.component"
                  :maxlength="30"
                  placeholder="请填写组件路径"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item name="query" label="路由参数" :rules="[{}]">
              <a-input
                  v-model:value="menuAddUpdateForm.data.query"
                  :maxlength="30"
                  placeholder="请填写路由参数"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item
                name="isFrame"
                label="是否为外链"
                :rules="[{ required: true, message: '是否为外链不能为空！' }]"
            >
              <a-radio-group
                  v-model:value="menuAddUpdateForm.data.isFrame"
                  :options="fatherPageData.sysYesNoDict"
                  option-type="button"
                  button-style="solid"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item
                name="menuType"
                label="菜单类型"
                :rules="[{ required: true, message: '菜单类型不能为空！' }]"
            >
              <a-select
                  v-model:value="menuAddUpdateForm.data.menuType"
                  :options="fatherPageData.menuTypeDict"
                  placeholder="请选择菜单类型"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item
                name="visible"
                label="是否显示"
                :rules="[{ required: true, message: '是否显示不能为空！' }]"
            >
              <a-radio-group
                  v-model:value="menuAddUpdateForm.data.visible"
                  :options="fatherPageData.sysYesNoDict"
                  option-type="button"
                  button-style="solid"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item
                name="status"
                label="菜单状态"
                :rules="[{ required: true, message: '菜单状态不能为空！' }]"
            >
              <a-radio-group
                  v-model:value="menuAddUpdateForm.data.status"
                  :options="fatherPageData.sysNormalDisableDict"
                  option-type="button"
                  button-style="solid"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item name="perms" label="权限标识" :rules="[{}]">
              <a-input
                  v-model:value="menuAddUpdateForm.data.perms"
                  :maxlength="30"
                  placeholder="请填写权限标识"
              />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item name="icon" label="菜单图标" :rules="[{}]">
              <a-space size="large">
                <component
                    :is="iconComponent"
                    v-if="menuAddUpdateForm.data.icon"
                    style="font-size: 20px;"
                />
                <a-button type="dashed" @click="showIconModal">
                  选择图标
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item name="remark" label="备注" :rules="[{}]">
              <a-textarea
                  v-model:value="menuAddUpdateForm.data.remark"
                  placeholder="请填写备注"
                  :rows="3"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 图标选择模态框 -->
    <a-modal
        v-model:visible="iconModalVisible"
        title="选择图标"
        :width="800"
        :footer="null"
        :destroy-on-close="true"
    >
      <a-input-search
          v-model:value="iconSearch"
          placeholder="搜索图标"
          style="margin-bottom: 16px;"
          @search="filterIcons"
      />
      <div class="icon-list">
        <a-tooltip
            v-for="icon in filteredIcons"
            :key="icon"
            :title="icon"
        >
          <component
              :is="allIcons[icon]"
              class="icon-item"
              @click="selectIcon(icon)"
          />
        </a-tooltip>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue';
import BearJiaUtil from '@/utils/BearJiaUtil.js';
import { listMenu as getMenuTreeselect, getMenu, addMenu, updateMenu } from '@/api/system/menu';
import { message } from 'ant-design-vue';
import { handleTree } from '@/utils/bearjia.js';
import * as allIcons from '@ant-design/icons-vue'; // 导入所有 Ant Design 图标

// 父页面公用数据
const fatherPageData = defineProps({
  sysYesNoDict: Array,
  sysShowHideDict: Array,
  menuTypeDict: Array,
  sysNormalDisableDict: Array,
});

const emit = defineEmits(['refreshFatherPageTable']);

// 当前页面使用的数据
const pageData = reactive({
  title: '新增页面',
  visible: false,
  operateType: '',
  menusDict: [],
});

// 新增修改表单
const menuAddUpdateFormRef = ref();
const menuAddUpdateForm = reactive({
  data: { isFrame: '1', visible: '0', status: '0' },
});

// 重置表单
const resetMenuAddUpdateForm = () => {
  BearJiaUtil.resetFormFieldsToEmpty(menuAddUpdateForm.data);
};

// 动态计算当前图标组件
const iconComponent = computed(() => {
  const iconName = menuAddUpdateForm.data.icon;
  return iconName && allIcons[iconName] ? allIcons[iconName] : null;
});

// 图标选择相关
const iconModalVisible = ref(false);
const iconSearch = ref('');
const iconList = Object.keys(allIcons).filter((key) => key.endsWith('Outlined')); // 只使用 Outlined 图标
const filteredIcons = ref(iconList);

const showIconModal = () => {
  iconModalVisible.value = true;
  filteredIcons.value = iconList; // 重置为完整列表
};

const filterIcons = () => {
  const searchValue = iconSearch.value.toLowerCase();
  filteredIcons.value = iconList.filter((icon) =>
      icon.toLowerCase().includes(searchValue)
  );
};

const selectIcon = (icon) => {
  menuAddUpdateForm.data.icon = icon;
  iconModalVisible.value = false;
  iconSearch.value = ''; // 清空搜索
};

// 打开新增窗口
const openAddModal = () => {
  menuAddUpdateForm.data.isFrame = '1';
  menuAddUpdateForm.data.visible = '0';
  menuAddUpdateForm.data.status = '0';
  pageData.operateType = 'add';
  pageData.title = '新增菜单';
  getMenuTreeselect().then((response) => {
    pageData.menusDict = handleTree(response.data, 'menuId');
    pageData.menusDict.push({ menuId: 0, menuName: '无' });
    pageData.visible = true;
  });
};

// 打开修改窗口
const openUpdateModal = (record) => {
  pageData.operateType = 'update';
  pageData.title = '修改菜单';
  getMenu(record.menuId).then((response) => {
    menuAddUpdateForm.data = response.data;
    getMenuTreeselect().then((response) => {
      pageData.menusDict = handleTree(response.data, 'menuId');
      pageData.menusDict.push({ menuId: 0, menuName: '无' });
      pageData.visible = true;
    });
  });
};

// 点击窗口确认
const clickModalOk = () => {
  menuAddUpdateFormRef.value
      .validate()
      .then(() => {
        if (pageData.operateType === 'add') {
          addMenu(menuAddUpdateForm.data).then(() => {
            pageData.visible = false;
            resetMenuAddUpdateForm();
            emit('refreshFatherPageTable');
            BearJiaUtil.messageSuccess('新增操作成功。');
          });
        } else if (pageData.operateType === 'update') {
          updateMenu(menuAddUpdateForm.data).then(() => {
            pageData.visible = false;
            resetMenuAddUpdateForm();
            emit('refreshFatherPageTable');
            BearJiaUtil.messageSuccess('修改操作成功。');
          });
        }
      })
      .catch((info) => {
        console.log('Validate Failed:', info);
      });
};

// 点击窗口取消
const handleModalCancel = () => {
  resetMenuAddUpdateForm();
  pageData.visible = false;
};

// 暴露方法
defineExpose({
  openAddModal,
  openUpdateModal,
});
</script>

<style lang="less" scoped>
.icon-list {
  max-height: 400px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.icon-item {
  font-size: 24px;
  cursor: pointer;
  padding: 8px;
  transition: all 0.3s;

  &:hover {
    color: #1890ff;
    background: #f0f0f0;
    border-radius: 4px;
  }
}
</style>